/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Commons;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import Commons.Logging.*;
import java.util.Iterator;

/**Questa classe implementa la scrittura su i file XML.
 * Al suo interno presenta degli attributi che definiscono
 * il WriterXML ,come il path su cui verra crato il file ed
 * il contatore dei Log.
 *
 * @author Team5
 */
public class WriterXML {
    private String pathFileXML;
    private int ContatoreLog=0;
    private int ContatoreObj=0;
    private File filelog;

    /**Costruttore di default
     *
     */
    public WriterXML(){
        this.pathFileXML="/home/carlo/Scrivania/test2.xml";
    }
    /**Costruttore in cui passo il path su cui voglio scrivere
     *
     * @param pathFileXML
     */
    public WriterXML(String pathFileXML){
        this.pathFileXML=pathFileXML;
    }
    /**Comando che inizializza l'esecuzione dei log sui i file XML
     *
     */
    
    public void startXML(){
        FileWriter file = null;
        try {
            filelog = new File(this.pathFileXML);
            file = new FileWriter(filelog);
            XMLOutputFactory f;
            XMLStreamWriter w;
            f = XMLOutputFactory.newInstance();
            w = f.createXMLStreamWriter(file);
            w.writeStartDocument();
            w.writeCharacters("\n");
            w.writeDTD("<!DOCTYPE logs SYSTEM " + '"' + "LogDTD.dtd" + '"' + " >");
            w.writeCharacters("\n");
            w.writeStartElement("logs");
            w.writeCharacters("\n");
            w.close();
        } catch (XMLStreamException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                file.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
    }
     
     
    /**Metodo che inizializza il generico oggetto che verrà scritto su XML
     *
     */

    public void startObjXML(){
        FileWriter file = null;
        try {
            filelog = new File(this.pathFileXML);
            file = new FileWriter(filelog);
            XMLOutputFactory f;
            XMLStreamWriter w;
            f = XMLOutputFactory.newInstance();
            w = f.createXMLStreamWriter(file);
            w.writeStartDocument();
            w.writeCharacters("\n");
            w.writeDTD("<!DOCTYPE logs SYSTEM " + '"' +"list"+"DTD.dtd" + '"' + " >");
            w.writeCharacters("\n");
            w.writeStartElement("list");
            w.writeCharacters("\n");
            w.close();
        } catch (XMLStreamException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                file.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
    /**Metodo che implementa la scrittura del generico log
     *
     * @param log che si vuole scrivere in XML
     */
    
    public void writeLogXML(Log log){
            
            FileWriter file = null;
            try {
                file = new FileWriter(this.filelog, true);
                XMLOutputFactory f;
                XMLStreamWriter w;
                System.out.println(log.toString());
                f = XMLOutputFactory.newInstance();
                w = f.createXMLStreamWriter(file);
                w.writeStartElement("log");
                w.writeCharacters("\n");
                w.writeStartElement("tipoEntita");
                w.writeCharacters(log.getTipoEntita());
                w.writeEndElement();
                w.writeCharacters("\n");
                w.writeStartElement("idEntita");
                w.writeCharacters(log.getIdEntita());
                w.writeEndElement();
                w.writeCharacters("\n");
                w.writeStartElement("numerosequenza");
                w.writeCharacters(this.ContatoreLog + "");
                w.writeEndElement();
                w.writeCharacters("\n");
                w.writeStartElement("operazione");
                w.writeCharacters(log.getOperazione());
                w.writeEndElement();
                w.writeCharacters("\n");
                w.writeStartElement("timestamp");
                w.writeCharacters(log.getTimestamp());
                w.writeEndElement();
                w.writeCharacters("\n");
                if (log.getClass().getSimpleName().equalsIgnoreCase("LogStatoCoda")) {
                    LogStatoCoda lsc = (LogStatoCoda) log;
                    w.writeStartElement("numerootaleoggettiinseriti");
                    w.writeCharacters(lsc.getNumeroTotaleOggettiInseriti() + "");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("numerototaleoggettiincoda");
                    w.writeCharacters(lsc.getNumeroAttualeOggettiInCoda() + "");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                }
                w.writeEndElement();
                w.writeCharacters("\n");
                w.close();
            } catch (XMLStreamException ex) {
                java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    file.close();
                } catch (IOException ex) {
                    java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    }
     
    /**Metodo che implementa la scrittura in XML di un generico file
     *
     * @param obj
     */
    public void writeObjXML(Object obj) throws IOException{
           FileWriter file = null;
            try {
            
            XMLOutputFactory f;
            XMLStreamWriter w;
            file = new FileWriter(this.filelog, true);
            
            
               
                if (obj.getClass().getSimpleName().equalsIgnoreCase("log")){
                Log log=(Log)obj;
                System.out.println(log.toString());
                f = XMLOutputFactory.newInstance();
                w = f.createXMLStreamWriter(file);

                w.writeStartElement("log");
                w.writeCharacters("\n");
                w.writeStartElement("tipoEntita");
                w.writeCharacters(log.getTipoEntita());
                w.writeEndElement();
                w.writeCharacters("\n");
                w.writeStartElement("idEntita");
                w.writeCharacters(log.getIdEntita());
                w.writeEndElement();
                w.writeCharacters("\n");
                w.writeStartElement("numerosequenza");
                w.writeCharacters(this.ContatoreLog + "");
                w.writeEndElement();
                w.writeCharacters("\n");
                w.writeStartElement("operazione");
                w.writeCharacters(log.getOperazione());
                w.writeEndElement();
                w.writeCharacters("\n");
                w.writeStartElement("timestamp");
                w.writeCharacters(log.getTimestamp());
                w.writeEndElement();
                w.writeCharacters("\n");
                if (obj.getClass().getSimpleName().equalsIgnoreCase("LogStatoCoda")) {
                    LogStatoCoda lsc = (LogStatoCoda) log;
                    w.writeStartElement("numerootaleoggettiinseriti");
                    w.writeCharacters(lsc.getNumeroTotaleOggettiInseriti() + "");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("numerototaleoggettiincoda");
                    w.writeCharacters(lsc.getNumeroAttualeOggettiInCoda() + "");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                }
                w.writeEndElement();
                w.writeCharacters("\n");
                w.close();
                }
                if (obj.getClass().getSimpleName().equalsIgnoreCase("TaskDescriptor")) {
                     file = new FileWriter(this.filelog, true);
                    TaskDescriptor td = (TaskDescriptor) obj;
                    System.out.println(td.toString());
                    f = XMLOutputFactory.newInstance();
                    w = f.createXMLStreamWriter(file);
                    w.writeStartElement("taskdescriptor");
                    w.writeCharacters("\n");
                    w.writeStartElement("id");
                    w.writeCharacters(td.getID() + "");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("identita");
                    w.writeCharacters(td.getCommand());
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("ramminima");
                    w.writeCharacters(td.getRamMinima()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("spaziosudisco");
                    w.writeCharacters(td.getSpazioOccupato()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("link");
                    if(td.getLink()!=null)
                    w.writeCharacters(td.getLink());
                    else
                    w.writeCharacters("linkvuoto");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("cpuminime");
                    w.writeCharacters(td.getnCpuMin()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("sistemioperativisupportati");
                    Iterator<String> iter=td.getSO().iterator();
                    while(iter.hasNext()){
                         w.writeCharacters("\n");
                         w.writeStartElement("sistemioperativo");
                         w.writeCharacters(iter.next());
                         w.writeEndElement();
                   
                    }
                    w.writeCharacters("\n");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.close();//AGGIUNTO OGGI
                }
                if (obj.getClass().getSimpleName().equalsIgnoreCase("WorkerDescriptor")) {
                    file = new FileWriter(this.filelog, true);
                    WorkerDescriptor wd=(WorkerDescriptor)obj;
                    f = XMLOutputFactory.newInstance();
                    w = f.createXMLStreamWriter(file);
                    w.writeStartElement("workerdescriptor");
                    w.writeCharacters("\n");
                    
                    w.writeStartElement("indirizzo");
                    w.writeCharacters(wd.getAddr().getIP());
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    
                    w.writeStartElement("portaudp");
                    w.writeCharacters(wd.getAddr().getPort()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    
                    w.writeStartElement("status");
                    w.writeCharacters(wd.getStatus().name()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    
                    w.writeStartElement("processiincoda");
                    w.writeCharacters(wd.getProcessiInCoda()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("cpuminima");
                    w.writeCharacters(wd.getnCpuMin()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("sistemiOperativo");
                    w.writeCharacters(wd.getSO());
                    w.writeEndElement();
                    w.writeCharacters("\n");;
                    w.writeStartElement("ramMinima");
                    w.writeCharacters(wd.getRamMinima()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("spazioSuDisco");
                    w.writeCharacters(wd.getSpazioOccupato()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.close();

                }
                if (obj.getClass().getSimpleName().equalsIgnoreCase("Workflow")) {
                     file = new FileWriter(this.filelog, true);
                    Workflow wf=(Workflow)obj;
                    f = XMLOutputFactory.newInstance();
                    w = f.createXMLStreamWriter(file);
                    w.writeStartElement("worfklow");
                    w.writeCharacters("\n");
                    w.writeStartElement("id");
                    w.writeCharacters(wf.getID()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeStartElement("numeroditask");
                    w.writeCharacters(wf.getTasks().size()+"");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.writeEndElement();
                    w.writeCharacters("\n");
                    w.flush();
                    
                }
            } catch (IOException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
            } catch (XMLStreamException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
               file.close();}
    }
    /**Metodo che implementa la chiusura del file XML
     *
     */
    
    public void closeXML() {
        FileWriter file = null;
        try {
            file = new FileWriter(this.filelog, true);
            XMLOutputFactory f;
            XMLStreamWriter w;
            f = XMLOutputFactory.newInstance();
            w = f.createXMLStreamWriter(file);
            w.writeEmptyElement("/logs>");
            w.close();
        } catch (XMLStreamException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                file.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        }
     
    /**Metodo che implementa la chiusura sul generico oggetto del file XML
     *
     */
    public void closeObjXML() {
        FileWriter file = null;
        
        try {
            file = new FileWriter(this.filelog, true);
            XMLOutputFactory f;
            XMLStreamWriter w;
            f = XMLOutputFactory.newInstance();
            w = f.createXMLStreamWriter(file);
            w.writeEmptyElement("/list>");
            w.close();
        } catch (XMLStreamException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                file.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(WriterXML.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        }

    /** Metodo che setta il contatore  dei Log
     *
     * @param contatore
     */
    public void setContatore(int i){
        this.ContatoreLog=i;
    }

}
